package com.onlinelearn.courseservice.service;

import com.onlinelearn.courseservice.dto.CourseDTO;
import com.onlinelearn.courseservice.model.Course;
import com.onlinelearn.courseservice.model.CourseCategory;
import com.onlinelearn.courseservice.model.CourseStatus;
import com.onlinelearn.courseservice.repository.CourseRepository;
import com.onlinelearn.courseservice.exception.CourseNotFoundException;
import com.onlinelearn.courseservice.exception.UnauthorizedAccessException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CourseService {
    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StorageService storageService;

    @Transactional
    public CourseDTO createCourse(CourseDTO courseDTO, Long teacherId) {
        // 验证课程数据
        validateCourseCreation(courseDTO);

        Course course = convertToEntity(courseDTO);
        course.setTeacherId(teacherId);
        course.setCreatedAt(LocalDateTime.now());
        
        // 设置默认状态为草稿
        course.setStatus(CourseStatus.DRAFT);

        Course savedCourse = courseRepository.save(course);
        return convertToDTO(savedCourse);
    }

    @Transactional
    public CourseDTO updateCourse(Long courseId, CourseDTO courseDTO, Long teacherId) {
        Course existingCourse = courseRepository.findById(courseId)
            .orElseThrow(() -> new CourseNotFoundException(courseId));

        // 验证教师权限
        if (!existingCourse.getTeacherId().equals(teacherId)) {
            throw new UnauthorizedAccessException("只有课程创建者可以修改课程");
        }

        // 更新课程信息
        updateCourseDetails(existingCourse, courseDTO);

        Course updatedCourse = courseRepository.save(existingCourse);
        return convertToDTO(updatedCourse);
    }

    @Transactional(readOnly = true)
    public List<CourseDTO> getCoursesByCategory(
        CourseCategory category, 
        CourseStatus status, 
        int page, 
        int size
    ) {
        List<Course> courses = courseRepository.findByCategoryAndStatus(
            category, 
            status, 
            PageRequest.of(page, size)
        );

        return courses.stream()
            .map(this::convertToDTO)
            .collect(Collectors.toList());
    }

    @Transactional(readOnly = true)
    public CourseDTO getCourseDetails(Long courseId) {
        Course course = courseRepository.findById(courseId)
            .orElseThrow(() -> new CourseNotFoundException(courseId));
        return convertToDTO(course);
    }

    @Transactional
    public void publishCourse(Long courseId, Long teacherId) {
        Course course = courseRepository.findById(courseId)
            .orElseThrow(() -> new CourseNotFoundException(courseId));

        // 验证教师权限
        if (!course.getTeacherId().equals(teacherId)) {
            throw new UnauthorizedAccessException("只有课程创建者可以发布课程");
        }

        // 验证课程是否满足发布条件
        validateCoursePublishEligibility(course);

        course.setStatus(CourseStatus.PUBLISHED);
        course.setPublishedAt(LocalDateTime.now());

        courseRepository.save(course);
    }

    @Transactional
    public void archiveCourse(Long courseId, Long teacherId) {
        Course course = courseRepository.findById(courseId)
            .orElseThrow(() -> new CourseNotFoundException(courseId));

        // 验证教师权限
        if (!course.getTeacherId().equals(teacherId)) {
            throw new UnauthorizedAccessException("只有课程创建者可以归档课程");
        }

        course.setStatus(CourseStatus.ARCHIVED);
        courseRepository.save(course);
    }

    private void validateCourseCreation(CourseDTO courseDTO) {
        // 课程标题长度验证
        if (courseDTO.getTitle() == null || courseDTO.getTitle().length() < 5) {
            throw new IllegalArgumentException("课程标题至少5个字符");
        }

        // 价格验证
        if (courseDTO.getPrice() != null && courseDTO.getPrice().compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("课程价格不能为负数");
        }
    }

    private void updateCourseDetails(Course existingCourse, CourseDTO courseDTO) {
        Optional.ofNullable(courseDTO.getTitle())
            .ifPresent(existingCourse::setTitle);
        
        Optional.ofNullable(courseDTO.getDescription())
            .ifPresent(existingCourse::setDescription);
        
        Optional.ofNullable(courseDTO.getCategory())
            .ifPresent(existingCourse::setCategory);
        
        Optional.ofNullable(courseDTO.getPrice())
            .ifPresent(existingCourse::setPrice);
    }

    private void validateCoursePublishEligibility(Course course) {
        // 检查是否有足够的课程内容
        if (course.getVideos().isEmpty()) {
            throw new IllegalStateException("发布课程前至少需要添加一个视频");
        }

        // 可以添加更多发布前的验证逻辑
    }

    private Course convertToEntity(CourseDTO dto) {
        Course course = new Course();
        course.setTitle(dto.getTitle());
        course.setDescription(dto.getDescription());
        course.setCategory(dto.getCategory());
        course.setPrice(dto.getPrice());
        return course;
    }

    private CourseDTO convertToDTO(Course course) {
        CourseDTO dto = new CourseDTO();
        dto.setId(course.getId());
        dto.setTitle(course.getTitle());
        dto.setDescription(course.getDescription());
        dto.setCategory(course.getCategory());
        dto.setPrice(course.getPrice());
        dto.setStatus(course.getStatus());
        dto.setTeacherId(course.getTeacherId());
        return dto;
    }
} 